package org.edu.modules.sxjy.controller;

import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.base.controller.BaseController;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.sxjy.common.noresubmit.CacheLock;
import org.edu.modules.sxjy.entity.VeCommon;
import org.edu.modules.sxjy.entity.VeCompany;
import org.edu.modules.sxjy.entity.VeEstate;
import org.edu.modules.sxjy.entity.VeTrade;
import org.edu.modules.sxjy.service.CacheKeyGenerator;
import org.edu.modules.sxjy.service.IVeBaseCompanyFilingService;
import org.edu.modules.sxjy.service.IVeBaseCompanyRecruitService;
import org.edu.modules.sxjy.service.IVeCompanyService;
import org.edu.modules.sxjy.service.IVeDgsxResidentTeacherService;
import org.edu.modules.sxjy.service.IVeEstateService;
import org.edu.modules.sxjy.service.IVeTradeService;
import org.edu.modules.sxjy.service.impl.CacheKeyGeneratorImp;
import org.edu.modules.sxjy.utils.PageResponseResult;
import org.edu.modules.sxjy.vo.VeCompanyAddVo;
import org.edu.modules.sxjy.vo.VeCompanyUpdateVo;
import org.edu.modules.sxjy.vo.VeCompanyUserVo;
import org.edu.modules.sxjy.vo.VeCompanyVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Api(tags={"企业信息管理"})
@RestController
@RequestMapping({"/sxjy/veCompany"})
@ApiSort(60)
public class VeCompanyController
        extends BaseController<VeCompany, IVeCompanyService>
{
    private static final Logger log = LoggerFactory.getLogger(VeCompanyController.class);
    @Autowired
    private IVeCompanyService veCompanyService;
    @Autowired
    private IVeEstateService veEstateService;
    @Autowired
    private IVeTradeService veTradeService;
    @Autowired
    private IVeBaseCompanyFilingService veBaseCompanyFilingService;
    @Autowired
    private IVeBaseCompanyRecruitService veBaseCompanyRecruitService;
    @Autowired
    private IVeDgsxResidentTeacherService veDgsxResidentTeacherService;

    @Bean
    public CacheKeyGenerator cacheKeyGenerator()
    {
        return new CacheKeyGeneratorImp();
    }

    @AutoLog("企业信息管理-导入数据")
    @ApiOperation(value="导入数据", notes="企业信息管理-导入数据")
    @RequestMapping(value={"/importExcel"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
    @CacheLock(prefix="redisLock.test", expire=1)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response)
    {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Iterator localIterator = fileMap.entrySet().iterator();
        if (localIterator.hasNext())
        {
            Map.Entry<String, MultipartFile> entity = (Map.Entry)localIterator.next();
            MultipartFile file = (MultipartFile)entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(1);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try
            {
                List<VeCompanyVo> listSysCategorys = ExcelImportUtil.importExcel(file.getInputStream(), VeCompanyVo.class, params);
                if (listSysCategorys.size() != 0)
                {
                    //lbh 2024/07/31 size >> Integer size
                    Integer size = 0;
                    for (Object localObject1 = listSysCategorys.iterator(); ((Iterator)localObject1).hasNext();)
                    {
                        VeCompanyVo veCompanyVo = (VeCompanyVo)((Iterator)localObject1).next();
                        boolean b = this.veCompanyService.setExcel(veCompanyVo);
                        if (b) {
                            size++;
                        }
                    }
                    return Result.ok("文件导入成功！数据行数：" + size);
                }
                return Result.error("文件导入失败");
            }
            catch (Exception e)
            {
                int size;
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败：" + e.getMessage());
            }
            finally
            {
                try
                {
                    file.getInputStream().close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    @AutoLog("企业信息管理-导出数据")
    @ApiOperation(value="导出数据", notes="企业信息管理-导出数据")
    @PostMapping({"/exportXls"})
    public ModelAndView exportXls(@RequestBody VeCommon veCommon)
    {
        List<VeCompanyVo> veCompanyList = this.veCompanyService.exportXls(veCommon);

        ModelAndView modelAndView = new ModelAndView(new JeecgEntityExcelView());

        modelAndView.addObject("fileName", "企业信息");
        modelAndView.addObject("entity", VeCompanyVo.class);
        LoginUser user = (LoginUser)SecurityUtils.getSubject().getPrincipal();
        modelAndView.addObject("params", new ExportParams("企业信息列表", "导出人:" + user.getRealname(), "导出信息"));
        modelAndView.addObject("data", veCompanyList);
        return modelAndView;
    }

    @AutoLog("企业信息管理-企业负责人回显")
    @ApiOperation(value="企业负责人回显", notes="企业信息管理-企业负责人回显")
    @GetMapping({"/setPrincipalEcho"})
    public Result<?> setPrincipalEcho(int id)
    {
        if (id != 0)
        {
            int cpUserId = this.veCompanyService.setPrincipalEcho(id);
            if (cpUserId != 0) {
                return Result.ok(Integer.valueOf(cpUserId));
            }
            return Result.OK();
        }
        return Result.error("该企业暂时未添加企业负责人");
    }

    @AutoLog("企业信息管理-设置企业负责人")
    @ApiOperation(value="设置企业负责人", notes="企业信息管理-设置企业负责人")
    @PutMapping({"/updatesSetPrincipal"})
    @CacheLock(prefix="redisLock.test", expire=1)
    public Result<?> updatesSetPrincipal(@RequestBody VeCompany veCompany)
    {
        if (veCompany != null)
        {
            VeCompany veCompanys = (VeCompany)this.veCompanyService.getById(Integer.valueOf(veCompany.getId()));
            veCompanys.setUserId(veCompany.getUserId());
            this.veCompanyService.updateById(veCompanys);
            return Result.ok("设置成功");
        }
        return Result.OK();
    }

    @AutoLog("企业信息管理-获取企业负责人名单")
    @ApiOperation(value="获取企业负责人名单", notes="企业信息管理-获取企业负责人名单")
    @GetMapping({"/updatesGetPrincipal"})
    public Result<?> updatesGetPrincipal(int cpId)
    {
        List<VeCompanyUserVo> veCompanyUserVoList = this.veCompanyService.getPrincipalName(cpId);
        return Result.ok(veCompanyUserVoList);
    }

    @AutoLog("企业信息管理-批量启用")
    @ApiOperation(value="批量启用", notes="企业信息管理-批量启用")
    @PutMapping({"/updateStart"})
    @CacheLock(prefix="redisLock.updateStart", expire=1)
    public Result<?> updateStart(@RequestBody List<VeCompany> veCompany)
    {
        if (veCompany.size() > 0)
        {
            this.veCompanyService.updateStart(veCompany);
            return Result.OK("启用成功");
        }
        return Result.error("启用失败");
    }

    @AutoLog("企业信息管理-批量禁用")
    @ApiOperation(value="批量禁用", notes="企业信息管理-批量禁用")
    @PutMapping({"/updateStop"})
    @CacheLock(prefix="redisLock.updateStop", expire=1)
    public Result<?> updateStop(@RequestBody List<VeCompany> veCompany)
    {
        if (veCompany.size() > 0)
        {
            this.veCompanyService.updateStop(veCompany);
            return Result.OK("禁用成功");
        }
        return Result.error("禁用失败");
    }

    @AutoLog("企业信息管理-查询列表")
    @ApiOperation(value="查询列表", notes="企业信息管理-查询列表")
    @GetMapping({"/selectAll"})
    public PageResponseResult selectAll(VeCompanyVo veCompanyVo, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, VeCommon veCommon)
    {
        Integer startLine = Integer.valueOf((pageNo.intValue() - 1) * pageSize.intValue());
        List<VeCompanyVo> veCompanyList = this.veCompanyService.selectAll(veCompanyVo, startLine, pageSize, veCommon);
        if ((Objects.isNull(veCompanyList)) && (veCompanyList.size() <= 0)) {
            return new PageResponseResult(Integer.valueOf(1), 1, 0, Result.OK());
        }
        int total = this.veCompanyService.getSumPage(veCompanyVo, veCommon);
        double totals = total;
        double pageSizes = pageSize.intValue();
        double totalPage = Math.ceil(totals / pageSizes);
        return new PageResponseResult(pageNo, (int)totalPage, total, Result.OK(veCompanyList));
    }

    @AutoLog("企业信息管理-选择企业列表")
    @ApiOperation(value="选择企业列表", notes="企业信息管理-选择企业列表")
    @GetMapping({"/selectCpList"})
    public PageResponseResult selectCpList(VeCompanyVo veCompanyVo, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, VeCommon veCommon)
    {
        return this.veCompanyService.selectCpList(veCompanyVo, pageNo, pageSize, veCommon);
    }

    @AutoLog("企业信息管理-通过id查询")
    @ApiOperation(value="通过id查询", notes="企业信息管理-通过id查询")
    @GetMapping({"/queryById"})
    public Result<?> queryById(@RequestParam(name="id", required=true) String id)
    {
        VeCompany veCompany = (VeCompany)this.veCompanyService.getById(id);
        if (veCompany == null) {
            return Result.OK();
        }
        return Result.OK(veCompany);
    }

    @AutoLog("企业信息管理-获得所属行业名称")
    @ApiOperation(value="获得所属行业名称", notes="企业信息管理-获得所属行业名称")
    @GetMapping({"/geTradeName"})
    public Result<?> geTradeName()
    {
        List<VeTrade> list = this.veTradeService.list();
        return Result.OK(list);
    }

    @AutoLog("企业信息管理-获得产业名称")
    @ApiOperation(value="获得产业名称", notes="企业信息管理-获得产业名称")
    @GetMapping({"/getEstateName"})
    public Result<?> getEstateName()
    {
        List<VeEstate> list = this.veEstateService.list();
        return Result.OK(list);
    }

    @AutoLog("企业信息管理-获取企业名称以及id")
    @ApiOperation(value="获取企业名称以及id", notes="企业信息管理-获取企业名称以及id")
    @GetMapping({"/getCpName"})
    public Result<?> getCpName()
    {
        List<VeCompany> veCompanyList = this.veCompanyService.list();
        return Result.OK(veCompanyList);
    }

    @AutoLog("企业信息管理-新增信息")
    @ApiOperation(value="新增信息", notes="企业信息管理-新增信息")
    @PostMapping({"/add"})
    @CacheLock(prefix="redisLock.add", expire=1)
    public Result<?> add(@RequestBody VeCompanyAddVo veCompanyAddVo)
    {
        if (veCompanyAddVo != null)
        {
            this.veCompanyService.saves(veCompanyAddVo);
            return Result.OK("添加成功！");
        }
        return Result.error("添加失败");
    }

    @AutoLog("企业信息管理-编辑回显")
    @ApiOperation(value="编辑回显", notes="企业信息管理-编辑回显")
    @GetMapping({"/udpateEcho"})
    public Result<?> updateEcho(int id)
    {
        if (id != 0)
        {
            VeCompanyUpdateVo veCompanyUpdateVo = this.veCompanyService.editEcho(id);
            return Result.OK(veCompanyUpdateVo);
        }
        return Result.error("编辑失败");
    }

    @AutoLog("企业信息管理-编辑")
    @ApiOperation(value="编辑", notes="企业信息管理-编辑")
    @PutMapping({"/edit"})
    @CacheLock(prefix="redisLock.edit", expire=1)
    public Result<?> edit(@RequestBody VeCompanyUpdateVo veCompanyUpdateVo)
    {
        if (veCompanyUpdateVo != null)
        {
            this.veCompanyService.edit(veCompanyUpdateVo);
            return Result.OK("编辑成功！");
        }
        return Result.error("编辑失败!");
    }

    @AutoLog("企业信息管理-通过id删除")
    @ApiOperation(value="通过id删除", notes="企业信息管理-通过id删除")
    @DeleteMapping({"/delete"})
    @Transactional
    public Result<?> delete(@RequestParam(name="id", required=true) String id)
    {
        this.veBaseCompanyFilingService.deleteByCpId(id);
        this.veBaseCompanyRecruitService.deleteByCpId(id);
        this.veDgsxResidentTeacherService.deleteByCpId(id);

        return this.veCompanyService.unityRemoveBatchById(id);
    }

    @AutoLog("企业信息管理-批量删除")
    @ApiOperation(value="批量删除", notes="企业信息管理-批量删除")
    @DeleteMapping({"/deleteBatch"})
    public Result<?> deleteBatch(@RequestParam(name="ids", required=true) String ids)
    {
        Result result = this.veCompanyService.unityRemoveBatch(ids);
        if (result.getCode().intValue() == 500) {
            return result;
        }
        String[] array = ids.split(",");
        if (array.length > 0)
        {
            this.veBaseCompanyFilingService.deleteByCpIds(array);
            this.veBaseCompanyRecruitService.deleteByCpIds(array);
            this.veDgsxResidentTeacherService.deleteByCpIds(array);
        }
        return this.veCompanyService.unityRemoveBatch(ids);
    }

    @AutoLog("企业信息管理-回显企业管理员的企业信息")
    @ApiOperation(value="回显企业管理员的企业信息", notes="企业信息管理-回显企业管理员的企业信息")
    @GetMapping({"/cpAdmincpNameEcho"})
    public Result<?> cpAdmincpNameEcho(String userId, String userType)
    {
        return this.veCompanyService.cpAdmincpNameEcho(userId, userType);
    }
}
